package com.epfresh.activity;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.baidu.speech.EventListener;

import com.baidu.speech.EventManager;
import com.baidu.speech.EventManagerFactory;
import com.baidu.speech.asr.SpeechConstant;
import com.epfresh.R;
import com.epfresh.adapter.DeliveryStoreListAdapter;
import com.epfresh.api.adapter.CommonAdapter;
import com.epfresh.api.adapter.ViewHolder;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.TagPager;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.api.utils.VerificationUtils;
import com.epfresh.api.widget.MsgView;
import com.epfresh.api.widget.list.LoadMoreListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.api.widget.tablayout.utils.UnreadMsgUtils;
import com.epfresh.basedialog.CustomDialog;
import com.epfresh.bean.AddCarResponse;
import com.epfresh.bean.CarCntResponse;
import com.epfresh.bean.ContentEntity;
import com.epfresh.bean.ListGoods;
import com.epfresh.bean.VoiceResult;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.CartHelper;
import com.epfresh.global.DataManager;
import com.epfresh.utils.FormatUtil;
import com.epfresh.views.FakeAddImageView;
import com.epfresh.views.PointFTypeEvaluator;
import com.epfresh.views.dialog.MsgDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

public class CenterSearchActivity extends BaseActivity implements LoadMoreListView.IXListViewListener, DataManager.OnCartCountChangeListener ,EventListener {

    static final String TAG = "OrderSearchActivity";

    //购物车数量
    MsgView msgCount;
    //购物车图标
   // ImageView ivCart;
    ImageView ivBack;


    EditText etContent;
    //View tvSearch;
    //    TextView tvCart;
    ImageView ivDelete;
//    View rlHistory, rlContent;
    View rlContent;
    ListView lvHistory;
    LoadMoreListView lvContent;

    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    List<String> historyList = new ArrayList<String>();
    StringAdapter historyAdapter;
    String historyTogether;
    ArrayList<ListGoods> goodsLists;
    private DeliveryStoreListAdapter adapterGoods;
    protected View mainView;
    protected View vException;
    protected TextView tvExceptionDescription;
    protected ImageView ivExceptionIcon;
    private ProgressBar pb;
    private int requestSucceedCount = 0;
    private int PAGE_SIZE = 10;

    String storeId;
    boolean isAcceptOrder;
    private TagPager tagPager = new TagPager();

    private int serviceStoreId;


    private View rl_tips;
    private ImageView img_voice_identify;
    private TextView txt_tip1,txt_tip2,txt_tip3,txt_tip4,txt_tip5;
    private GifImageView img_gif_voice;
    private TextView txt_voice_search;
    private ImageView img_cancel;
    private TextView tv_search_title;

    private boolean isVoiceRunning = false;
    private boolean haveRecording = false;
    private boolean activeShutdown = false;
    private EventManager asr;
    private Handler handler = new Handler();
    InputMethodManager inputMethodManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (savedInstanceState != null) {
            storeId = savedInstanceState.getString("storeId");
            isAcceptOrder = savedInstanceState.getBoolean("isAcceptOrder", true);
        } else {
            storeId = getIntent().getStringExtra("storeId");
//            isAcceptOrder = getIntent().getBooleanExtra("isAcceptOrder", true);
        }

        initShare();
        initView();
        initVoiceConfigure();
        DataManager.getInstance().registerMsgView("OrderSearchActivity", this);


        updateCount(DataManager.getInstance().getCartCnt());

        requestCount();

        DataManager.getInstance().clearCollectMap();
        inputMethodManager.showSoftInput(etContent, InputMethodManager.SHOW_FORCED);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("storeId", storeId);
        outState.putBoolean("isAcceptOrder", isAcceptOrder);
        super.onSaveInstanceState(outState);
    }


    private void initView() {
        setContentView(R.layout.activity_center_search);

        rl_tips = findViewById(R.id.rl_tips);
        img_voice_identify = findViewById(R.id.img_voice_identify);
        txt_tip1 = findViewById(R.id.txt_tip1);
        txt_tip2 = findViewById(R.id.txt_tip2);
        txt_tip3 = findViewById(R.id.txt_tip3);
        txt_tip4 = findViewById(R.id.txt_tip4);
        txt_tip5 = findViewById(R.id.txt_tip5);
        img_gif_voice = findViewById(R.id.img_gif_voice);
        txt_voice_search = findViewById(R.id.txt_voice_search);
        img_cancel = findViewById(R.id.img_cancel);
        tv_search_title=findViewById(R.id.tv_search_title);

        txt_voice_search.setOnClickListener(this);
        img_cancel.setOnClickListener(this);
        tv_search_title.setOnClickListener(this);

        ((EditText) findViewById(R.id.et_content)).setHint("请输入商品名称");

        msgCount = (MsgView) findViewById(R.id.msg);
//        ivCart = (ImageView) findViewById(R.id.iv_cart);
//        ivCart.setOnClickListener(this);
        initCartView();

        rlContent = findViewById(R.id.rl_content);
//        rlHistory = findViewById(R.id.rl_history);
        lvHistory = (ListView) findViewById(R.id.lv_history);
        lvContent = (LoadMoreListView) findViewById(R.id.lv_content);
        historyAdapter = new StringAdapter(this, historyList, R.layout.item_string);
        initHistory();
        lvHistory.setAdapter(historyAdapter);
        ivBack = (ImageView) findViewById(R.id.iv_back);
        etContent = (EditText) findViewById(R.id.et_content);
//        tvSearch = findViewById(R.id.tv_search);
//        tvSearch.setOnClickListener(this);
//        tvCart = (TextView) findViewById(R.id.tv_total);
//        tvCart.setOnClickListener(this);
        ivDelete = (ImageView) findViewById(R.id.iv_delete);
        ivDelete.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        mainView = findViewById(R.id.fragment_ptr_home_ptr_frame);
        initHeadView();
        tagPager.setNumber(0);
        goodsLists = new ArrayList<>();

        adapterGoods = new DeliveryStoreListAdapter(this, goodsLists);
//        adapter = new OrderAdapter(mContext, goodsLists, R.layout.item_center_search);

        adapterGoods.setOnCollectListener(new DeliveryStoreListAdapter.OnCartAddListener() {
            @Override
            public void onCartAdd(int type, int position, ListGoods goods, View v) {

                if (goods != null) {


                    reqCollect(goods);
                }


            }
        });
        lvContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
                if (i < goodsLists.size()) {
                    ListGoods listGoods = CenterSearchActivity.this.goodsLists.get(i);
                    String id = listGoods.getId();
                    Intent intent = new Intent(CenterSearchActivity.this, DetailGoodsActivity.class);
                    intent.putExtra("storeId", listGoods.getStoreId());
                    intent.putExtra("id", id + "");
                    intent.putExtra("promotionItemId", listGoods.getPromotionItemId());
                    intent.putExtra("serviceStoreId",serviceStoreId);
                    startActivity(intent);
                }
            }
        });
        lvContent.setXListViewListener(this);
        lvContent.setAdapter(adapterGoods);
        View rlNoDate = findViewById(R.id.rl_nodate);
        lvContent.setEmptyView(rlNoDate);

        etContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH) {

                    if (TextUtils.isEmpty(etContent.getText().toString())) {
                        return true;
                    }
                    tv_search_title.performClick();
//                    tagPager.setNumber(0);
//                    lvContent.resetNoMore();
//                    requestSucceedCount = 0;
////                    rlHistory.setVisibility(View.GONE);
//                    rlContent.setVisibility(View.VISIBLE);
//                    loadData(0);
//                    editor.putString("share_center_history", sharedPreferences.getString("share_center_history", "") + "," + etContent.getText().toString());
//                    editor.commit();
                    return true;
                }
                return false;
            }
        });

        initGoodsAdapter();

    }

    private void initGoodsAdapter() {
        adapterGoods.setOnAddClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                if (!isAcceptOrder) {
                    T.toast("暂不接单");
                } else {
//                    addCart(listGoods.get(i));
                    ListGoods goods = goodsLists.get(i);
                    reqCartCnt(goods.getMoq(), goods);
                }
            }
        });

        adapterGoods.setOnCartAddListener(new DeliveryStoreListAdapter.OnCartAddListener() {
            @Override
            public void onCartAdd(int type, int position, ListGoods goods, View v) {
                DataManager.getInstance().oftenListReFresh = true;

                if (type == 1) {//购物车手动输入

                    openDialog(goods);
                } else if (type == 2) {//添加
                    addCartCnt(goods, true, v);
                } else if (type == 3) {//减少
                    addCartCnt(goods, false, v);

                } else if (type == 5) {
                    String id = goods.getId();
                    Intent intent = new Intent(CenterSearchActivity.this, DetailGoodsActivity.class);
                    intent.putExtra("id", id + "");
                    intent.putExtra("storeId", goods.getStoreId());
                    intent.putExtra("promotionItemId", goods.getPromotionItemId());
                    intent.putExtra("serviceStoreId",serviceStoreId);
                    startActivity(intent);

                } else if (type == 10) {

                    if (goods.getShoppingCarId() == null) {
                        Log.e("getShoppingCarId", "_____null___" + goods.getShoppingCarId());
                        return;
                    }
                    openMsgDialog(goods, goods.getFastMessages());
                }
            }
        });

    }


    MsgDialog msgDialog;
    String msgNow;

    private void openMsgDialog(ListGoods goods, List<String> list) {
        //if (msgDialog == null)
        msgDialog = new MsgDialog(this);
        msgDialog.setOnCommitListener(new MsgDialog.OnCommitListener() {
            @Override
            public void onCommit(String msg, String goodsId) {
                msgDialog.dismiss();
                msgNow = msg;
                saveMsg(msg, goodsId);
            }
        });
        msgDialog.show(goods.getShoppingCarId(), list, goods.getMsg());
    }

    HashSet<String> goodCollectSet = new HashSet<>();

    private void reqCollect(ListGoods goods) {

        if (goodCollectSet.contains(goods.getUniqueKey())) {
            return;
        }
        Boolean show = goods.isShow();
        goods.setShow(!show);
        adapterGoods.notifyDataSetChanged();
        goodCollectSet.add(goods.getUniqueKey());
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(AppPurchaseRouterConstant.cmd_store_product_frequent);


//        private Long promotionItemId;//促销场次ID
//        private Long promotionId;//促销ID
//        private Integer promotionType;//促销场次ID
        re.putParameter("productId", goods.getId());

        re.putParameter("show", !show);

        RequestTag tag = new RequestTag();
        tag.arg1 = "product/frequent";
        tag.arg2 = goods;


        request(re, tag, new OnRequestListener<Map<String, Boolean>>() {
            @Override
            public Map<String, Boolean> jsonToObj(String responseStr) {
                return JsonUtils.fromJsonMap(responseStr, Boolean.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                if (tag != null && tag instanceof RequestTag) {
                    RequestTag requestTag = (RequestTag) tag;
                    tag = requestTag.arg2;
                    if (tag != null && tag instanceof ListGoods) {
                        ListGoods g = (ListGoods) tag;
                        g.setShow(!g.isShow());
                        goodCollectSet.remove(g.getUniqueKey());
                        adapterGoods.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                if (tag != null && tag instanceof RequestTag) {
                    RequestTag requestTag = (RequestTag) tag;
                    tag = requestTag.arg2;
                    if (tag != null && tag instanceof ListGoods) {
                        ListGoods g = (ListGoods) tag;
                        g.setShow(!g.isShow());
                        goodCollectSet.remove(g.getUniqueKey());
                        adapterGoods.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onStart(Object tag) {

            }

            @Override
            public void onResponse(ResponseEntity<Map<String, Boolean>> response, Object tag) {

                ListGoods g = null;
                if (tag != null && tag instanceof RequestTag) {
                    RequestTag requestTag = (RequestTag) tag;
                    tag = requestTag.arg2;
                    if (tag != null && tag instanceof ListGoods) {
                        g = (ListGoods) tag;
                        goodCollectSet.remove(g.getUniqueKey());
                    }
                }

                if (response != null) {
                    Map<String, Boolean> responseElement = response.getResponseElement();
                    if (responseElement != null) {
                        Boolean show = responseElement.get("show");
                        if (show != null) {
                            if (g != null) {
                                DataManager.getInstance().putCollectMap(g.getUniqueKey(), show);
                                g.setShow(show);
                                adapterGoods.notifyDataSetChanged();

                            }

                        }
                    }
                }
            }
        });

    }


    OnRequestListener<Map<String, Object>> onSaveMsgRequestListener = new OnRequestListener<Map<String, Object>>() {
        @Override
        public Map<String, Object> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<Map<String, Object>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            toast(o + "");//arg + ",请点击重试"

        }

        @Override
        public void onStart(Object o) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<Map<String, Object>> responseEntity, Object o) {
            hideProgressDialog();
            if (msgDialog != null)
                msgDialog.dismiss();

            Map<String, Object> responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {
                Object success = responseElement.get("success");
                if (success != null && success instanceof Boolean && ((Boolean) success)) {
/*                    groupList.get(msgPosition/1000).getResult().get(msgPosition%1000).setMerMsg(msgNow);
                    adapter.notifyDataSetChanged();*/
                    requestCount();
                }
            }
        }
    };

    public void saveMsg(String msg, String goodsId) {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(AppPurchaseRouterConstant.cmd_order_cart_saveMsg);
        re.putParameter("merMsg", msg);
        re.putParameter("shoppingCarId", goodsId);
        ApplicationHelper.getInstance().requestSilent(re, "appOrder/createMerMsg", onSaveMsgRequestListener);
    }


    public void openDialog(final ListGoods cartGood) {

        final Dialog dialog = new Dialog(this, R.style.no_title_dialog);

        dialog.setContentView(R.layout.dialog_cart_add);
        ImageView ivAdd = (ImageView) dialog.findViewById(R.id.iv_add);
        ImageView ivRemove = (ImageView) dialog.findViewById(R.id.iv_remove);

        final EditText ed = (EditText) dialog.findViewById(R.id.ed_price);

        ed.setText(FormatUtil.subZeroAndDot(cartGood.getCount() + ""));
        ed.setSelection(ed.length());
        CashierInputFilter cashierInputFilter = new CashierInputFilter();
        cashierInputFilter.MAX_VALUE = 999999;
        ed.setFilters(new InputFilter[]{cashierInputFilter});
        ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = ed.getText().toString();
                double min = cartGood.getMoq();
                double incr = cartGood.getIncr();
                double cnt = min;
                Log.d("cnt", "s:" + s);
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }
                double amount = cnt;


//                if (FormatUtil.remainderZero(amount, cartGood.getInventoryAmount()) > 0) {
//                    amount = cartGood.getInventoryAmount();
//                }

                amount = FormatUtil.countAdd(amount, incr);
//                if (FormatUtil.remainderZero(amount, cartGood.getInventoryAmount()) > 0) {
//                    amount = cartGood.getInventoryAmount();
//                }


                cartGood.setCount(amount);
                ed.setText(FormatUtil.subZeroAndDot(amount + ""));
                ed.setSelection(ed.length());
            }
        });
        ivRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = ed.getText().toString();
                double min = cartGood.getMoq();
                double incr = cartGood.getIncr();
                double cnt = min;
                Log.d("cnt", "s:" + s);
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }
                double amount = cnt;
                if (amount < cartGood.getMoq()) {
                    amount = cartGood.getMoq();
                }

                amount = FormatUtil.countSubtract(amount, incr);
                if (amount < cartGood.getMoq()) {
                    amount = cartGood.getMoq();
                }
                cartGood.setCount(amount);
                ed.setText(FormatUtil.subZeroAndDot(amount + ""));
                ed.setSelection(ed.length());
            }
        });
        dialog.findViewById(R.id.negativeButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(ed.getApplicationWindowToken(), 0);
                }
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.positiveButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                double productCount = cartGood.getCount();
                String s = ed.getText().toString();
                double min = cartGood.getMoq();
                double incr = cartGood.getIncr();
                double cnt = min;
                Log.d("cnt", "s:" + s);
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }
                if (cnt < 0.01 || cnt < min) {
                    T.toast("不能少于" + FormatUtil.subZeroAndDot(min + ""));
                    cnt = FormatUtil.countFormat(cnt, incr, min);
                    ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setSelection(ed.getText().length());
                    return;
                }


//                if (cnt > cartGood.getInventoryAmount()) {
//                    T.toast("超过库存");
//                    cnt = FormatUtil.countFormat(cartGood.getInventoryAmount(), incr, min);
//
//                    ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
//                    ed.setSelection(ed.getText().length());
//                    return;
//                }
                incr = incr < 0.01 ? min : incr;

                if (FormatUtil.isRemainder(cnt, incr, min)) {
                    cnt = FormatUtil.countFormat(cnt, incr, min);
                    Log.e("cnt:", "cnt:" + FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setSelection(ed.getText().length());
                    return;
                }

//                cartGood.setCount(cnt);
                reqCartCnt(cnt, cartGood);
                adapterGoods.notifyDataSetChanged();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(ed.getApplicationWindowToken(), 0);
                }
                dialog.dismiss();
            }
        });

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {

            }
        });

        dialog.show();

    }

    public void addCartCnt(ListGoods goods, boolean isAdd, View v) {
        double min = goods.getMoq();
        double incr = goods.getIncr();
        double amount = goods.getCount();


        if (isAdd) {
            amount = FormatUtil.countAdd(amount, incr);
        } else {
            amount = FormatUtil.countAdd(amount, -incr);
        }

//        if (FormatUtil.remainderZero(amount, goods.getInventoryAmount()) > 0) {
//            amount = goods.getInventoryAmount();
//            T.toast("库存不够");
//        } else
        if (isAdd) {
            addAnim(v);
        }
        if (isAdd && FormatUtil.remainderZero(amount, goods.getMoq()) < 0) {
            amount = min;
        }


        if (!isAdd && (FormatUtil.remainderZero(amount, 0) <= 0 || FormatUtil.remainderZero(amount, min) < 0)) {
            amount = 0;
            reqCartCnt(amount, goods);
            return;
        }

//        amount = FormatUtil.countFormat(amount, incr, min);
        amount = FormatUtil.countFormat(amount, incr, min, goods.getInventoryAmount());
        reqCartCnt(amount, goods);

    }


    View shoppingCartView;
    ViewGroup mainLayout;

    private void initCartView() {
        shoppingCartView = findViewById(R.id.iv_cart);
        mainLayout = (ViewGroup) findViewById(R.id.rl_main_layout);
    }

    public void addAnim(View view) {
        int[] addLocation = new int[2];
        int[] cartLocation = new int[2];
//        int[] lvCartLocation = new int[2];
        view.getLocationInWindow(addLocation);
        shoppingCartView.getLocationInWindow(cartLocation);
//        lvCart.getLocationInWindow(lvCartLocation);

        PointF startP = new PointF();
        PointF endP = new PointF();
        PointF controlP = new PointF();

        startP.x = addLocation[0];
        startP.y = addLocation[1];
        endP.x = cartLocation[0] + LocalDisplay.dp2px(10);
        endP.y = cartLocation[1] - this.getResources().getDimensionPixelSize(R.dimen.bottom_nav_ic_height);
        controlP.x = endP.x;
        controlP.y = startP.y;

        final FakeAddImageView fakeAddImageView = new FakeAddImageView(this);
        mainLayout.addView(fakeAddImageView);
        fakeAddImageView.setImageResource(R.drawable.cart_bezier);
        fakeAddImageView.getLayoutParams().width = LocalDisplay.dp2px(10);
        fakeAddImageView.getLayoutParams().height = LocalDisplay.dp2px(10);
        fakeAddImageView.setVisibility(View.VISIBLE);
        ObjectAnimator addAnimator = ObjectAnimator.ofObject(fakeAddImageView, "mPointF",
                new PointFTypeEvaluator(controlP), startP, endP);
        addAnimator.setInterpolator(new AccelerateInterpolator());
        addAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                fakeAddImageView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                fakeAddImageView.setVisibility(View.GONE);
                mainLayout.removeView(fakeAddImageView);
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        ObjectAnimator scaleAnimatorX = new ObjectAnimator().ofFloat(shoppingCartView, "scaleX", 0.6f, 1.0f);
        ObjectAnimator scaleAnimatorY = new ObjectAnimator().ofFloat(shoppingCartView, "scaleY", 0.6f, 1.0f);
        scaleAnimatorX.setInterpolator(new AccelerateInterpolator());
        scaleAnimatorY.setInterpolator(new AccelerateInterpolator());
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(scaleAnimatorX).with(scaleAnimatorY).after(addAnimator);
        animatorSet.setDuration(340);
        animatorSet.start();

    }


    private void initHeadView() {
        ptrFrameLayout = (PtrFrameLayout) findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }

    private PtrFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, lvContent, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    public void refresh() {
        lvContent.resetNoMore();
        loadData(0);
    }

    @Override
    public void onLoadMore() {
        int number = tagPager.getNumber();
        loadData(number + 1);
    }

    public void updateViewStatus(RequestTag requestTag) {
        ptrFrameLayout.refreshComplete();
        if (tagPager.isLast()) {
            lvContent.noMore();
        } else {
            lvContent.stopLoadMore();
        }
    }

    private void updateCount(int count) {
        UnreadMsgUtils.showLitter(msgCount, count, false);

    }

    @Override
    public void onCartCountChange(int count) {
        updateCount(count);
    }


    void loadData(int page) {
        RequestEntityPurchase<Map<String, String>> entity = new RequestEntityPurchase<>();
        Map<String, String> map = new HashMap<>();
        map.put("accountId", getUser().getAccountId());
        if (TextUtils.isEmpty(etContent.getText().toString()))
            return;
        map.put("title", etContent.getText().toString());
        map.put("pageNumber", page + "");
        map.put("storeId", getIntent().getStringExtra("storeId"));
        map.put("pageSize", PAGE_SIZE + "");
        map.put("sortProperty", "isRecommended");
        map.put("sortDirection", "DESC");
        entity.setCmd(AppPurchaseRouterConstant.cmd_store_product_list);
        entity.setParameters(map);
        RequestTag requestTag = new RequestTag();
        requestTag.tag = "product/list";
        requestTag.action = page;
        requestTag.type = RequestTag.TYPE_CURRENT;
        request(entity, requestTag, onRequestListener);
    }

    private OnRequestListener onRequestListener = new OnRequestListener<ContentEntity<ListGoods>>() {
        @Override
        public ContentEntity<ListGoods> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<ContentEntity<ListGoods>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            if (requestSucceedCount == 0) {
                showExceptionView(R.mipmap.goods_no, "网络问题,请点击重试", HttpRequest.FAIL_NET_FAULT);
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (requestSucceedCount == 0) {
                showExceptionView(R.mipmap.goods_no, arg + "", HttpRequest.FAIL_NET_FAULT);//arg + ",请点击重试"
            }
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
        }

        @Override
        public void onStart(Object tag) {
            if (requestSucceedCount == 0) {
                showProgressView();
            }
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<ListGoods>> response, Object tag) {
            //页面第一次调用网络请求接口并成功
            if (requestSucceedCount == 0) {
                showMainView();
            }
            requestSucceedCount++;
            RequestTag requestTag = (RequestTag) tag;
            if (requestTag.action == 0) {
                goodsLists.clear();
            }
            ContentEntity<ListGoods> orderResponse = response.getResponseElement();
            List<ListGoods> content = orderResponse.getContent();
            serviceStoreId = orderResponse.getServiceStoreId();
            tagPager.setLast(orderResponse.getLast());
            tagPager.setNumber(orderResponse.getNumber());
            tagPager.setSize(orderResponse.getSize());
            tagPager.setTotalElements(orderResponse.getTotalElements());
            goodsLists.addAll(content);
            if (content != null && content.size() > 0) {
                ListGoods listGoods = content.get(0);
                isAcceptOrder = listGoods.isAcceptOrders();
            }
            adapterGoods.notifyDataSetChanged();
            if (orderResponse.getNumber() == 0) {
                if (resumeFlag) {
                    resumeFlag = false;
                } else {
                    lvContent.setSelection(0);
                }
            }
            updateViewStatus(requestTag);

            updateCount(DataManager.getInstance().getCartCnt());
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(etContent.getWindowToken(), 0);
            requestCount();
        }
    };

    boolean resumeFlag = false;

    void initShare() {
        sharedPreferences = getSharedPreferences("center_search_history", Context.MODE_PRIVATE); //私有数据
        editor = sharedPreferences.edit();//获取编辑器
    }

    void initHistory() {
        historyTogether = sharedPreferences.getString("share_center_history", "");
        Log.i("historyTogether", historyTogether + "——————————————————————————————————");
        historyList.clear();
        if (!historyTogether.equals("")) {
            ArrayList<String> flag = new ArrayList<>();
            flag.addAll(Arrays.asList(historyTogether.split(",")));
            for (int i = flag.size() - 1; i > 0; i--) {
                if (!historyList.contains(flag.get(i)))
                    historyList.add(flag.get(i));
                if (historyList.size() == 10)
                    break;
            }
        }
        historyAdapter.notifyDataSetChanged();
    }

    protected View getToolBar() {
        //      View actionbar = this.inflaterView(R.layout.toolbar_dc_search, (ViewGroup) null);
/*        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(-1, this.getResources().getDimensionPixelSize(com.epfresh.api.R.dimen.action_bar_height));
        actionbar.setLayoutParams(lp);*/
        return null;
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                // 返回上一页
                finish();
                break;
            case R.id.tv_search:
                if (TextUtils.isEmpty(etContent.getText().toString())) {
                    return;
                }
                if (!VerificationUtils.isValid(etContent.getText().toString())) {
                    toast("请删除特殊字符");
                    return;
                }
                tagPager.setNumber(0);
                lvContent.resetNoMore();
                requestSucceedCount = 0;
//                rlHistory.setVisibility(View.GONE);
                rlContent.setVisibility(View.VISIBLE);
                loadData(0);
                editor.putString("share_center_history", sharedPreferences.getString("share_center_history", "") + "," + etContent.getText().toString());
                editor.commit();
                break;
            case R.id.iv_delete:
                CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
                builder.setMessage("确定要删除历史搜索吗？");//设置显示的内容
                builder.setTitleVisible(false);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        editor.putString("share_center_history", "");
                        editor.commit();
                        initHistory();
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//响应事件
                        dialog.dismiss();
                    }

                });
                builder.create().show();
                break;
            case R.id.iv_cart:
                cart();
                break;
            case R.id.tv_total:
                cart();
                break;
            case R.id.txt_voice_search:
                if (!isVoiceRunning) {
                    audioPermissionCheck();
                }else {
                    activeShutdown = true;
                    voiceActiveStop();
                }
                break;

            case R.id.img_cancel:
                voiceCancel();
                break;
            case R.id.tv_search_title:
                // 搜商品
                if (TextUtils.isEmpty(etContent.getText().toString())) {
                    return;
                }
                if (!VerificationUtils.isValid(etContent.getText().toString())){
                    toast("请删除特殊字符");
                    return ;
                }
                Intent goodsList = new Intent(this, SearchGoodsActivity.class);
                goodsList.putExtra("title", etContent.getText().toString());
                goodsList.putExtra("storeId",storeId);
                goodsList.putExtra("sortProperty","isRecommended");
                startActivity(goodsList);
                inputMethodManager.hideSoftInputFromWindow(etContent.getWindowToken(), 0);
                break;
        }
    }

    public void cart() {
        if (ApplicationHelper.getInstance().getUser().getAccess_token() == null || "".equals(ApplicationHelper.getInstance().getUser().getAccess_token())) {
            Intent intent = new Intent(this, LoginActivity.class);
            intent.putExtra("relogin", true);
            startActivity(intent);
            return;
        }

        Intent intent = new Intent(this, CartActivity.class);
        intent.putExtra("home_tab_index", 2);
        startActivity(intent);
    }

    class StringAdapter extends CommonAdapter<String> {
        public StringAdapter(Context context, List<String> historyList, int a) {
            super(context, historyList, a);
        }

        @Override
        public void convert(ViewHolder holder, final String bean) {
            holder.setText(R.id.tv_string, bean);
            holder.setOnClickListener(R.id.tv_string, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    etContent.setText(bean);
                    etContent.setSelection(bean.length());
                    //tvSearch.performClick();
                }
            });
        }
    }

    public void requestCount() {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(AppPurchaseRouterConstant.cmd_order_cart_cnt);
//        re.putParameter("storeId", storeDetail.getId());
        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
        re.putParameter("wholeSalesType", "2");
        ApplicationHelper.getInstance().requestSilent(re, "appOrder/shoppingCarCntNew", onCartCntRequestListener);
    }


    OnRequestListener<CarCntResponse> onCartCntRequestListener = new OnRequestListener<CarCntResponse>() {
        @Override
        public CarCntResponse jsonToObj(String s) {
            return new Gson().fromJson(s, CarCntResponse.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

        }

        @Override
        public void onStart(Object o) {

        }

        @Override
        public void onResponse(ResponseEntity<CarCntResponse> responseEntity, Object o) {
//            dcCnt = responseEntity.getResponseElement();
            carCntResponse = responseEntity.getResponseElement();
            if (carCntResponse != null) {
                carCntResponse.init();
            }
            updateCnt();
        }
    };

    CarCntResponse carCntResponse;

    public void updateCnt() {

        if (carCntResponse != null) {

            if (goodsLists != null) {
                for (int i = 0; i < goodsLists.size(); i++) {
                    ListGoods item = goodsLists.get(i);
                    if (cartHelper != null && cartHelper.isRequesting(item.getUniqueKey())) {
                        continue;
                    }
                    item.setCount(carCntResponse.getGoodsCount(item.getIdPlus()));
                    Log.e("listGoods", "cnt:" + item.getCount() + "---id:" + item.getId());
                    item.setShoppingCarId(carCntResponse.getShopingCarId(item.getIdPlus()));
                    if (carCntResponse != null && carCntResponse.getMerMsgMap() != null)
                        item.setMsg(carCntResponse.getMerMsgMap().get(item.getShoppingCarId()));
                }
            }

            if (adapterGoods != null) {
                adapterGoods.notifyDataSetChanged();
            }
        }

    }


    OnRequestListener<AddCarResponse> onCntRequestListener = new OnRequestListener<AddCarResponse>() {
        @Override
        public AddCarResponse jsonToObj(String s) {
            return new Gson().fromJson(s, AddCarResponse.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            hideProgressDialog();
            RequestTag tag = null;
            if (o1 instanceof RequestTag) {
                tag = (RequestTag) o1;
                String arg1 = tag.arg1;
                Object arg2 = tag.arg2;
                Object o2 = tag.tag;
                if (arg1 != null && o2 != null && o2 instanceof ListGoods) {
                    ListGoods goods = (ListGoods) o2;
//                        BigDecimal a = new BigDecimal(arg1).setScale(2, BigDecimal.ROUND_HALF_UP);
                    if (arg2 != null && arg2 instanceof Double) {
//                        goods.setCount((Double) arg2);
                        responseCartCnt(true, goods, -1);
                        adapterGoods.notifyDataSetChanged();

                        T.toast(goods.getTitle() + " 添加购物车失败");
                    }
                }
            }
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            hideProgressDialog();
            RequestTag tag = null;
            if (i / 10 == 40) {
                T.toast(o + "");
            }
            if (o1 instanceof RequestTag) {
                tag = (RequestTag) o1;
                String arg1 = tag.arg1;
                Object arg2 = tag.arg2;
                Object o2 = tag.tag;
                if (arg1 != null && o2 != null && o2 instanceof ListGoods) {
                    ListGoods goods = (ListGoods) o2;
//                        BigDecimal a = new BigDecimal(arg1).setScale(2, BigDecimal.ROUND_HALF_UP);
                    if (arg2 != null && arg2 instanceof Double) {
//                        goods.setCount((Double) arg2);
                        responseCartCnt(true, goods, -1);
                        adapterGoods.notifyDataSetChanged();

                        if (i / 100 != 4) {
                            T.toast(goods.getTitle() + " 添加购物车失败");
                        }
                    }
                }
            }
        }

        @Override
        public void onStart(Object o) {
            //hideProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<AddCarResponse> responseEntity, Object o) {
            hideProgressDialog();

            AddCarResponse responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {
                DataManager.getInstance().oftenListReFresh = true;

                RequestTag tag = null;
                if (o instanceof RequestTag) {
                    tag = (RequestTag) o;
                    String arg1 = tag.arg1;
                    Object o2 = tag.tag;
                    if (arg1 != null && o2 != null && o2 instanceof ListGoods) {
                        ListGoods goods = (ListGoods) o2;
//                        BigDecimal a = new BigDecimal(arg1).setScale(2, BigDecimal.ROUND_HALF_UP);
                        goods.setCount(responseElement.getProductCnt());
                        goods.setShoppingCarId(responseElement.getShoppingCarId());
//                        DataManager.getInstance().setCartCntStatus(responseElement.getshoppingCarCnt());
                        DataManager.getInstance().updateCartCnt();

                        responseCartCnt(false, goods, responseElement.getProductCnt());
                        if (carCntResponse == null) {
                            adapterGoods.notifyDataSetChanged();
                        } else {
                            carCntResponse.putCategoryCount(responseElement.getCategoryId(), responseElement.getCategoryCnt());
                            carCntResponse.putTopCategoryCount(responseElement.getTopCategoryId(), responseElement.getTopCategoryCnt());
                            carCntResponse.putPromotionCount(responseElement.getTopCategoryId(), responseElement.getPromotionCnt());
                            carCntResponse.putGoodsCount(goods.getIdPlus(), goods.getCount());
                            carCntResponse.putShopingCarId(goods.getIdPlus(), responseElement.getShoppingCarId());
                            if (responseElement.getProductCnt() == 0) {
                                carCntResponse.getMerMsgMap().remove(responseElement.getShoppingCarId());
                            }
                            updateCnt();
                        }
                    }
                }


            }
        }
    };
    CartHelper cartHelper = new CartHelper();

    public void reqCartCnt(double productCount, ListGoods goods) {
        if (goods == null) {
            return;
        }

        if (goods != null) {
            goods.setCount(productCount);
            adapterGoods.notifyDataSetChanged();
        }
        if (!cartHelper.checkIsCartRequesting(goods)) {
            updateCartCnt(productCount, goods);
        } else {

        }
    }

    public void responseCartCnt(boolean isFail, ListGoods goods, double cnt) {
        if (isFail) {
            cartHelper.responseCartFail(goods);
        } else {
            cartHelper.responseCartSuccess(goods, cnt);
        }
    }

    public void updateCartCnt(double productCount, ListGoods goods) {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(AppPurchaseRouterConstant.cmd_order_cart_add);
/*        re.putParameter("promotionItemId", goods.getPromotionItemId());

        re.putParameter("shoppingCarId", goods.getShoppingCarId());
        re.putParameter("productUnitPrice", goods.getPriceOnly());
        re.putParameter("productId", goods.getId());
        re.putParameter("salesType", goods.getType());
        re.putParameter("versionId", goods.getLastSnapshotId());
        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        re.putParameter("productCount", productCount);
        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());*/
//        re.putParameter("specId", goods.getId());
        re.putParameter("specId", goods.getProductSpecPrice().getProductSpecId());
        if (serviceStoreId != -1) {
            re.putParameter("serviceStoreId", serviceStoreId);
        }
        if (goods.getPromotion() != null)
            re.putParameter("specPromotionItemId", goods.getPromotion().getItemId());
        re.putParameter("count", productCount);
        RequestTag tag = new RequestTag();
        tag.tag = goods;
//        tag.tag = "appOrder/updateShoppingCarProductCount";
        tag.arg1 = productCount + "";
        tag.arg2 = productCount;
//        tag.arg2 = goods;
        if (cartHelper != null && goods != null) {
            cartHelper.updateRequest(goods.getUniqueKey());
        }
        request(re, tag, onCntRequestListener);

    }


    //************************************************************百度语音搜索*********************************************************************************

    private void initVoiceConfigure() {
        asr = EventManagerFactory.create(this, "asr");
        asr.registerListener(this);
    }

    /**
     * 按钮状态切换
     *
     * @param voiceCheck 是否可以录音 true：可以 false：不可以
     */
    private void updateButtonStatus(boolean voiceCheck) {
        if (voiceCheck) {
            txt_voice_search.setText("语音搜索");
            txt_voice_search.setTextColor(Color.parseColor("#24af75"));
            txt_voice_search.setBackgroundResource(R.drawable.btn_voice_search);
            Drawable drawable = CenterSearchActivity.this.getResources().getDrawable(R.mipmap.icon_microphone_green);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            txt_voice_search.setCompoundDrawables(drawable, null, null, null);
            img_cancel.setVisibility(View.GONE);
            isVoiceRunning = false;
        } else {
            txt_voice_search.setText("结束录音");
            txt_voice_search.setTextColor(Color.parseColor("#ffffff"));
            txt_voice_search.setBackgroundResource(R.drawable.btn_voice_no_search);
            Drawable drawable = CenterSearchActivity.this.getResources().getDrawable(R.mipmap.icon_microphone_white);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            txt_voice_search.setCompoundDrawables(drawable, null, null, null);
            img_cancel.setVisibility(View.VISIBLE);
            isVoiceRunning = true;
        }
    }

    /**
     * 基于SDK集成 发送开始事件
     * 点击开始按钮
     * 测试参数填在这里
     */
    private void voiceStart() {
        updateButtonStatus(false);
        //基于SDK集成,设置识别参数
        Map<String, Object> params = new LinkedHashMap<>();
        params.put(SpeechConstant.ACCEPT_AUDIO_VOLUME, false);
        String json; // 可以替换成自己的json
        json = new JSONObject(params).toString(); // 这里可以替换成你需要测试的json
        asr.send(SpeechConstant.ASR_START, json, null, 0, 0);
    }

    /**
     * 点击停止按钮
     * 基于SDK集成 发送停止事件
     */
    private void voiceActiveStop() {
        updateButtonStatus(true);
        asr.send(SpeechConstant.ASR_STOP, null, null, 0, 0);
    }

    private void voiceAutoStop(boolean haveResult) {
        if (!activeShutdown) {
            updateButtonStatus(true);
        }
        if (haveResult) {
            rl_tips.setVisibility(View.GONE);
        }
        activeShutdown = false;
        asr.send(SpeechConstant.ASR_STOP, null, null, 0, 0);
    }

    private void voiceCancel() {
        updateButtonStatus(true);
        rl_tips.setVisibility(View.GONE);
        asr.send(SpeechConstant.ASR_CANCEL, null, null, 0, 0);
    }

    @Override
    public void onEvent(String name, String params, byte[] bytes, int offset, int length) {
        Log.i("voice_flag:",name);
        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_READY)) {
            //提示开始说话
            haveRecording = false;
            beginRecording();
        }

        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_END)) {
            //说话结束提示开始识别
            beginIdentify();
        }

        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_FINISH)) {
            if (!haveRecording) {
                showNoVoice();
            } else {
                showVoiceResult();
            }
        }
        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)) {

            if (params != null) {
                VoiceResult voiceResult = VoiceResult.parseJson(params);
                // 识别结果
                String[] results = voiceResult.getResultsRecognition();
                if (voiceResult.isFinalResult()) {
                    // 最终识别结果，长语音每一句话会回调一次
                    haveRecording = true;
                    txt_tip1.setText(results[0]);
                }
            }

        }
    }


    private void beginRecording() {
        rl_tips.setVisibility(View.VISIBLE);
        img_voice_identify.setVisibility(View.GONE);
        txt_tip1.setText("你可以试试这样说");
        txt_tip1.setTextColor(Color.parseColor("#313131"));
        txt_tip1.setVisibility(View.VISIBLE);
        txt_tip2.setVisibility(View.GONE);
        txt_tip3.setVisibility(View.VISIBLE);
        txt_tip4.setVisibility(View.VISIBLE);
        txt_tip5.setVisibility(View.VISIBLE);
        img_gif_voice.setVisibility(View.VISIBLE);
    }

    private void beginIdentify() {
        img_voice_identify.setVisibility(View.VISIBLE);
        txt_tip1.setVisibility(View.GONE);
        txt_tip2.setVisibility(View.GONE);
        txt_tip3.setVisibility(View.GONE);
        txt_tip4.setVisibility(View.GONE);
        txt_tip5.setVisibility(View.GONE);
        img_gif_voice.setVisibility(View.GONE);
    }

    private void showVoiceResult() {
        img_voice_identify.setVisibility(View.GONE);
        txt_tip1.setTextColor(Color.parseColor("#313131"));
        txt_tip1.setVisibility(View.VISIBLE);
        txt_tip2.setVisibility(View.GONE);
        txt_tip3.setVisibility(View.GONE);
        txt_tip4.setVisibility(View.GONE);
        txt_tip5.setVisibility(View.GONE);
        img_gif_voice.setVisibility(View.GONE);
        etContent.setText(txt_tip1.getText().toString());
        autoSearch(txt_tip1.getText().toString());
    }

    private void showNoVoice() {
        img_voice_identify.setVisibility(View.GONE);
        txt_tip1.setTextColor(Color.parseColor("#f13d1a"));
        txt_tip1.setText("未检测到语音");
        txt_tip1.setVisibility(View.VISIBLE);
        txt_tip2.setVisibility(View.VISIBLE);
        txt_tip3.setVisibility(View.VISIBLE);
        txt_tip4.setVisibility(View.VISIBLE);
        txt_tip5.setVisibility(View.VISIBLE);
        img_gif_voice.setVisibility(View.GONE);
        voiceAutoStop(false);
    }

    private void autoSearch(final String keyword) {

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                voiceAutoStop(true);
                toSearch(keyword);
            }
        },1000);

    }


    private void toSearch(String keyword) {
        etContent.setText(keyword);
        etContent.setSelection(keyword.length());
        tv_search_title.performClick();
    }

    private void audioPermissionCheck() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
        } else {
            voiceStart();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    voiceStart();
                } else {
                    T.toast("请到设置中打开应用语音权限！");
                }
                break;
        }
    }

    @Override
    protected void onPause() {
        asr.send(SpeechConstant.ASR_CANCEL, null, null, 0, 0);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        DataManager.getInstance().removeMsgView("OrderSearchActivity");
        if (img_gif_voice != null) {
            ((GifDrawable)img_gif_voice.getDrawable()).stop();
        }
        asr.send(SpeechConstant.ASR_CANCEL, null, null, 0, 0);
        asr.unregisterListener(this);
        super.onDestroy();
    }

}
